package top.lisicheng.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import top.lisicheng.model.CommonResult;
import top.lisicheng.model.Payment;

import javax.annotation.Resource;

/**
 * @author Lisicheng
 */
@RestController
@Slf4j
@RequestMapping("order")
public class OrderController {

    private final static String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    // private final static String PAYMENT_URL = "http://cloud-payment-service";


    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("create")
    public CommonResult<Payment> create(Payment payment) {
        log.info("123");
        return restTemplate.postForObject(PAYMENT_URL + "/payment/add", payment, CommonResult.class);
    }

    @GetMapping("get")
    public CommonResult get(Long id) {
        return restTemplate.getForEntity(PAYMENT_URL + "/payment/get?id=" + id, CommonResult.class).getBody();
    }

    @GetMapping("discovery")
    public Object discovery() {
        for (String service : discoveryClient.getServices()) {
            System.out.println("serviceId:" + service);
            for (ServiceInstance instance : discoveryClient.getInstances(service)) {
                System.out.println("ServiceInstance:" + instance);
            }
            System.out.println("***********************");
        }
        return discoveryClient;
    }
}
